package com.chanzany.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.chanzany.srb.core.mapper.DictMapper;
import com.chanzany.srb.core.pojo.dto.ExcelDictDTO;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author ChanZany
 * @Date 2021/4/13 10:12
 * @Version 1.0
 */
@Slf4j
@NoArgsConstructor
public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {
    //缓冲列表
    private List<ExcelDictDTO> cacheDictList = new ArrayList<>();
    //一次存储的数据条目数量
    private static final int BATCH_COUNT =5;

    private DictMapper dictMapper;

    //构造函数注入
    public ExcelDictDTOListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(ExcelDictDTO excelDictDTO, AnalysisContext analysisContext) {
        log.info("data:{}", excelDictDTO);
        cacheDictList.add(excelDictDTO);
        while (cacheDictList.size() >= BATCH_COUNT) {
            saveData();
            cacheDictList.clear();
        }
    }

    private void saveData() {
        // 调用mapper存储读取到的数据
        dictMapper.insertBatch(cacheDictList);
        log.info("{}条数据被存储到数据库", cacheDictList.size());

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //当最后剩余的数据记录数不足BATCH_SIZE时，最终一次存储剩余数据
        saveData();
        log.info("完成所有excelDict的读取...");
    }
}
